<?php 
namespace User\Controller;
use Think\Controller;
class ForgetController extends Controller{
	
	function _initialize() {
		//登录拦截，防止已经登录的再进入注册页面
		if($_SESSION['loginUser']){
			redirect('/user/setting.html'); //拦截到登录
			exit();
		}
	}
	
	public function index(){
		$this->display();
	}
	
	/**
	* 发送邮件
	*/
	function send_email(){
		$email = I('email');
		if(!$email) _apiReturn(0,"邮箱不能为空");
		if(isset($_SESSION['tmpUser']['sendTime'])){
			if($_SESSION['tmpUser']['sendTime'] + 60 > strtotime('now')){
				_apiReturn(0,'不要在一分钟内重复发送');
			}
		}
		$m = D('Users');
		$user = $m->where("email='".$email."'")->find();
		if($user){
			if($this->_sendRegEmail($user['uid'],$user['username'],$user['email'])){
				$_SESSION['tmpUser']['sendTime'] = strtotime('now');
				_apiReturn(1,'发送成功');
			}else{
				_apiReturn(0,'发送失败');
			}
		}else{
			_apiReturn(0,'邮箱不存在');
		}
		
	}

	/**
	* 发送邮件验证码
	*/
	public function _sendRegEmail($uid,$username,$email){
		$m = M('UsersInvitation');
		$map = array(
			'uid' => $uid,
			'hasuse' => 2
		);
		$codeInfo = $m->where($map)->find();
		if($codeInfo){
			$code = $codeInfo['invite_code'];
		}else{
			$code = $map['invite_code'] = get_rand_num(6);
			$map['create_time'] = $map['update_time'] = Date('Y-m-d H:i:s');
			$m->add($map); //填写进去
		}
		$tpl = F('Options/option_find_pwd_check_tpl');
		//替换username
		$tpl = str_replace("#username#",$username,$tpl);
		//替换code
		$tpl = str_replace("#code#",$code,$tpl);
		//将邮件发送出去
		return sendMail($email, F('Options/option_find_pwd_check_title'), $tpl);
	}

	/**
	* 校验验证码
	*/
	public function check_code_post(){
		if(IS_POST){
			$email = I('email');
			$pass = I('pass');
			$oldpass = I('repass');
			$code = I('code');
			if(!$email) _apiReturn(0,"邮箱不能为空");
			if(!$code) _apiReturn(0,'验证码不能为空');
			if(!$pass) _apiReturn(0,"密码不能为空");
			if($pass != $oldpass){
				_apiReturn(0,"两次密码不一致");
			}
			if(strlen($pass) < 6){
				_apiReturn(0,"密码长度不能小于6位");
			}
			if(strlen($pass) > 20){
				_apiReturn(0,"密码长度不能大于20位");
			}
			$m = M('UsersInvitation');
			$mm = D('Users');
			
			$has = $mm->where("email='".$email."'")->find();
			if(!$has) _apiReturn(0,'邮箱不存在');
			$salt = $has['salt'];
			$map = array(
				'uid' => $has['uid'],
				'hasuse' => 2,
				'invite_code' => $_POST['code']
			);
			if($m->where($map)->find()){
				//激活成功
				$data = array(
					'uid' => $has['uid'],
					'password' => md5(md5($pass).$salt)
				);
				$mm->save($data);
				//删除掉code
				$m->where($map)->delete(); 
				_apiReturn(1,"密码修改成功","","/user/login"); //激活成功
			}else{
				_apiReturn(0,"验证码错误");
			}
			
		}
	}
}
?>